﻿using Engine;
using Game.NetWork;
using Game.Server.Event;
using GameEntitySystem;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace Game.Server.Plugins
{
    public class ClearZHPlugin : ServerPlugin, ICreatureSpawnEventHandle
    {
        public override int Version => 10000;

        public override string Name => "生物和掉落物清理";

        public byte FirstLevel => 0;

        public static Dictionary<string, int> Parameters = new Dictionary<string, int>();

        public SubsystemPickables subsystemPickables;

        public static string ConfigFilePath => Storage.GetSystemPath(ServerManager.PluginsPath + "/Clear.json");

        public override void Initialize()
        {
            CreatureSpawnEventManager.AddObject(this);
        }

        public bool Update(SubsystemCreatureSpawn subsystemCreatureSpawn, float dt)
        {
            if(subsystemCreatureSpawn.m_subsystemTime.PeriodicGameTimeEvent((float)Parameters["Frequency"], 0))
            {
                if (subsystemPickables == null)
                {
                    subsystemPickables = subsystemCreatureSpawn.Project.FindSubsystem<SubsystemPickables>();
                }
                if (subsystemPickables.Pickables.Count > Parameters["PickablesWarnCount"])
                {
                    Log.Warning("现在世界中掉落物数量为" + subsystemPickables.Pickables.Count);
                }
                if(subsystemPickables.Pickables.Count > Parameters["PickablesClearCount"])
                {
                    subsystemPickables.m_pickables.Clear();
                    SubsystemGameWidgets subsystemGameWidgets = subsystemCreatureSpawn.Project.FindSubsystem<SubsystemGameWidgets>();
                    if (Parameters["AddMessage"] == 1)
                    {
                        if (CommonLib.WorkType == WorkType.Server)
                        {
                            subsystemGameWidgets.AddMessage($"掉落物数量超过{Parameters["PickablesClearCount"]}，正在清理...");
                        }
                    }
                }
                List<Entity> creatures = new List<Entity>();
                foreach(var entity in subsystemCreatureSpawn.Project.Entities)
                {
                    if (entity.FindComponent<ComponentCreature>() != null && entity.FindComponent<ComponentPlayer>() == null)
                    {
                        creatures.Add(entity);
                    }
                }
                if (creatures.Count > Parameters["CreaturesWarnCount"])
                {
                    Log.Warning("现在世界中生物数量为" + creatures.Count);
                }
                if (creatures.Count > Parameters["CreaturesClearCount"])
                {
                    foreach(var c in creatures)
                    {
                        Random random = new Random();
                        if (random.Bool(0.5f))
                        {
                            subsystemCreatureSpawn.Project.RemoveEntity(c, true);
                        }
                    }
                    SubsystemGameWidgets subsystemGameWidgets = subsystemCreatureSpawn.Project.FindSubsystem<SubsystemGameWidgets>();
                    if (Parameters["AddMessage"] == 1)
                    {
                        if (CommonLib.WorkType == WorkType.Server)
                        {
                            subsystemGameWidgets.AddMessage($"生物数量超过{Parameters["CreaturesClearCount"]}，正在随机清理....");
                        }
                    }
                }
            }
            return true;
        }

        public void InitCreatureTypes(SubsystemCreatureSpawn subsystemCreatureSpawn, List<SubsystemCreatureSpawn.CreatureType> creatureTypes)
        {
        }

        public override void Load()
        {
            if (File.Exists(ConfigFilePath))
            {
                using (StreamReader file = File.OpenText(ConfigFilePath))
                {
                    string jsonText = file.ReadToEnd();
                    Parameters = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonText);
                }
            }
            else
            {
                Parameters["Frequency"] = 5;
                Parameters["AddMessage"] = 1;
                Parameters["PickablesWarnCount"] = 100;
                Parameters["PickablesClearCount"] = 1000;
                Parameters["CreaturesWarnCount"] = 30;
                Parameters["CreaturesClearCount"] = 100;
            }
        }

        public override void Save()
        {
        }

        public void OnEntityAdded(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnEntityRemoved(SubsystemCreatureSpawn subsystemCreatureSpawn, Entity entity)
        {
        }

        public void OnPlayerSpawned(PlayerData playerData, Entity playerEntity, Vector3 position)
        {
        }
    }
}